#region Using

using System;
using System.Xml;
using System.IO;
using System.Globalization;
using System.Collections.Generic;
using System.Collections.Specialized;
using BlogEngine.Core;
using BlogEngine.Core.Providers.EloqueraProvider.Db;
using Eloquera.Client;
using System.Collections;

#endregion

namespace BlogEngine.Core.Providers
{
	/// <summary>
	/// A storage provider for BlogEngine that uses XML files.
	/// <remarks>
	/// To build another provider, you can just copy and modify
	/// this one. Then add it to the web.config's BlogEngine section.
	/// </remarks>
	/// </summary>
    public partial class EloqueraBlogProvider : BlogProvider
	{
		//private static string _Folder = System.Web.HttpContext.Current.Server.MapPath(BlogSettings.Instance.StorageLocation);

		internal string _Folder
		{
			get
			{
				string p =  StorageLocation().Replace("~/", "");
				return System.IO.Path.Combine(System.Web.HttpRuntime.AppDomainAppPath, p);
			}
		}

		/// <summary>
		/// Retrieves a post based on the specified Id.
		/// </summary>
		public override Post SelectPost(Guid id)
		{
            Parameters param = EqDb.CreateParameters();
            param["id"] = id;
            EqPost eqPost = (EqPost)EqDb.ExecuteScalar("select EqPost where Id = @id",param);
            if (eqPost == null)
                return null;
            Post post = new Post() {
                Id = eqPost.Id,
                Title = eqPost.Title,
                Description = eqPost.Description,
                Content = eqPost.Content,
                DateCreated = eqPost.DateCreated,
                DateModified = eqPost.DateModified,
                Author = eqPost.Author,
                IsPublished = eqPost.IsPublished,
                IsCommentsEnabled = eqPost.IsCommentsEnabled,
                Raters = eqPost.Raters,
                Rating = eqPost.Rating,
                Slug = eqPost.Slug,
            };
            post.Tags.AddRange(eqPost.Tags);
            foreach (var strKey in eqPost.Categories) {
                Guid key = new Guid(strKey);
                post.Categories.Add(Category.GetCategory(key));
            }
            
            post.NotificationEmails.AddRange(eqPost.Emails);

            param = EqDb.CreateParameters();
            param["id"] = id;
            IEnumerable eqComments = EqDb.ExecuteQuery("select EqComment where ParentId = @id", param);
            foreach (var obj in eqComments) {
                EqComment eqComment = (EqComment)obj;
                Comment comment = new Comment() {
                    Id = eqComment.Id,
                    ParentId = eqComment.ParentId,
                    Author = eqComment.Author,
                    Email = eqComment.Email,
                    Parent = post,
                    Country = eqComment.Country,
                    IP = eqComment.Ip,
                    IsApproved = eqComment.IsApproved,
                    Content = eqComment.Content,
                    DateCreated = eqComment.DateCreated
                };
                Uri website;
                if (Uri.TryCreate(eqComment.WebSite, UriKind.Absolute, out website))
                    comment.Website = website;
                else
                    comment.Website = null;
                post.Comments.Add(comment);
            }
            post.Comments.Sort();
			return post;
		}


		///// <summary>
		///// Retrieves the content of the post in order to lazy load.
		///// </summary>
		///// <param name="id"></param>
		///// <returns></returns>
		//public override string SelectPostContent(Guid id)
		//{
		//  string fileName = _Folder + "posts" + Path.DirectorySeparatorChar + id.ToString() + ".xml";
		//  Post post = new Post();
		//  XmlDocument doc = new XmlDocument();
		//  doc.Load(fileName);

		//  if (doc.SelectSingleNode("post/content") != null)
		//    return doc.SelectSingleNode("post/content").InnerText;

		//  return string.Empty;
		//}

		/// <summary>
		/// Inserts a new Post to the data store.
		/// </summary>
		/// <param name="post"></param>
		public override void InsertPost(Post post)
		{
            Parameters param = EqDb.CreateParameters();
            param["id"] = post.Id;
            EqPost eqPost = (EqPost)EqDb.ExecuteScalar("select EqPost where Id = @id", param);
            if (eqPost == null)
                eqPost = new EqPost();
            eqPost.Author = post.Author;
            eqPost.Title = post.Title;
            eqPost.Description= post.Description;
            eqPost.Content = post.Content;
            eqPost.IsPublished = post.IsPublished;
            eqPost.IsCommentsEnabled = post.IsCommentsEnabled;
            eqPost.DateCreated = post.DateCreated;
            eqPost.DateModified = post.DateModified;
            eqPost.Raters = post.Raters;
            eqPost.Rating = post.Rating;
            eqPost.Slug = post.Slug;
            eqPost.Tags = post.Tags.ToArray();
            List<string> lstEmails = new List<string>();
            foreach (var mail in post.NotificationEmails) {
                lstEmails.Add(mail);
            }
            eqPost.Emails = lstEmails.ToArray();

            IEnumerable eqComments = EqDb.ExecuteQuery("select EqComment where ParentId = @id", param);
            foreach (var obj in eqComments) {
                EqComment eqComment = (EqComment)obj;
                EqDb.Delete(eqComment);
            }
            List<string> lCats = new List<string>();
            foreach (var comment in post.Comments) {
                EqComment eqComment = new EqComment() {
                    Id = comment.Id,
                    ParentId = comment.ParentId,
                    Author = comment.Author,
                    Email = comment.Email,
                    Parent = eqPost,
                    Country = comment.Country,
                    Ip = comment.IP,
                    IsApproved = comment.IsApproved,
                    Content = comment.Content,
                    WebSite = comment.Website == null ? string.Empty:comment.Website.ToString(),
                    DateCreated = comment.DateCreated,
                };
                lCats.Add(eqComment.Id.ToString());
                EqDb.Store(eqComment);
            }
            eqPost.Categories = lCats.ToArray();
            EqDb.Store(eqPost);
		}


		/// <summary>
		/// Updates a Post.
		/// </summary>
		public override void UpdatePost(Post post)
		{
			InsertPost(post);
		}

		/// <summary>
		/// Deletes a post from the data store.
		/// </summary>
		public override void DeletePost(Post post)
		{

            Parameters param = EqDb.CreateParameters();
            param["id"] = post.Id;
            IEnumerable eqComments = EqDb.ExecuteQuery("select EqComment where ParentId = @id", param);
            foreach (var obj in eqComments) {
                EqComment eqComment = (EqComment)obj;
                EqDb.Delete(eqComment);
            }
            EqPost eqPost = (EqPost)EqDb.ExecuteScalar("select EqPost where Id = @id");
            if (eqPost != null) {
                EqDb.Delete(eqPost);
            }
        }

		/// <summary>
		/// Retrieves all posts from the data store
		/// </summary>
		/// <returns>List of Posts</returns>
		public override List<Post> FillPosts()
		{
            List<Post> posts = new List<Post>();
            IEnumerable eqPosts = EqDb.ExecuteQuery("select EqPost");
            foreach (var obj in eqPosts) {
                EqPost eqPost = (EqPost)obj;
                Post post = SelectPost(eqPost.Id);
                posts.Add(post);
            }
			posts.Sort();
			return posts;
		}

	}
}